package org.hbhk.hms.mq.tx.mq;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IPUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(IPUtils.class);

	private static String localIP = null;

	private IPUtils() {
	}

	public static String getIpAddress() {
		try {
			if (localIP != null) {
				return localIP;
			}
			localIP = InetAddress.getLocalHost().getHostAddress();
			while (localIP.startsWith("169.254")) {
				LOGGER.warn("鏃犳硶姝ｅ父鑾峰彇IP锛屽噯澶囬噸鏂拌幏鍙栥��");
				Thread.sleep(100);
				localIP = InetAddress.getLocalHost().getHostAddress();
			}
		} catch (UnknownHostException e) {

			LOGGER.error("鏃犳硶鎵惧埌褰撳墠涓绘満銆�", e);
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			LOGGER.error("绾跨▼鎿嶄綔涓柇", e);
		}
		return localIP;
	}

	private static void getIpAddress(StringBuilder ifConfig) throws UnknownHostException, SocketException {
		for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
			NetworkInterface intf = en.nextElement();
			extractGetIpAddress(intf, ifConfig);
		}
	}

	private static void extractGetIpAddress(NetworkInterface intf, StringBuilder ifConfig) {
		for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
			InetAddress inetAddress = enumIpAddr.nextElement();
			if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()
					&& inetAddress.isSiteLocalAddress()) {
				String[] itn = inetAddress.toString().split("/");
				String str = itn[1];
				if (str.length() < 16) {
					ifConfig.append(inetAddress.getHostAddress());
				}
			}
		}

	}
}
